package com.azure.bigstore.config;

import com.azure.bigstore.entity.Token;
import com.azure.bigstore.service.TokenService;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;

/**
 * Created by liuhuaibin on 2018/2/5.
 */
/*@Component
@WebFilter(urlPatterns = "/v1/cart",filterName = "tokenFilter")*/
public class TokenValidate implements Filter{

    @Autowired
    private TokenService tokenService;

    private static  final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("!!!!!!!!!!!");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;


        String tn = req.getParameter("tn");
        Token t = tokenService.findByToken(tn);
//        System.out.println("tn:"+tn+"  >>>  token:"+t.toString());

        if(t != null &&  t.getValidityTime().after(new Date())  ){
            long time = t.getValidityTime().getTime();
            t.setValidityTime(new Date(time+3600));
            tokenService.saveToken(t);
        }else{
            res.getWriter().print("-100");
        }

        filterChain.doFilter(req,res);

    }

    @Override
    public void destroy() {

    }
}
